<template>
  <div class="audit-log-container">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h2>审计日志</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleExport" v-if="checkPermission('audit:export')">
          <el-icon><Download /></el-icon>
          导出日志
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" layout="inline" size="small" @submit.prevent>
        <el-form-item label="操作用户">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入操作用户"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select
            v-model="searchForm.operationType"
            placeholder="请选择操作类型"
            clearable
            style="width: 180px"
          >
            <el-option label="登录" :value="1" />
            <el-option label="登出" :value="2" />
            <el-option label="新增" :value="3" />
            <el-option label="编辑" :value="4" />
            <el-option label="删除" :value="5" />
            <el-option label="查询" :value="6" />
            <el-option label="导入" :value="7" />
            <el-option label="导出" :value="8" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作结果">
          <el-select
            v-model="searchForm.operationResult"
            placeholder="请选择操作结果"
            clearable
            style="width: 180px"
          >
            <el-option label="成功" :value="1" />
            <el-option label="失败" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="searchForm.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 审计日志表格 -->
    <el-card class="table-card" shadow="hover">
      <el-table
        v-loading="loading"
        :data="auditLogList"
        style="width: 100%"
        border
        stripe
        size="small"
      >
        <el-table-column prop="id" label="日志ID" width="120" />
        <el-table-column prop="username" label="操作用户" width="150" />
        <el-table-column prop="ip" label="IP地址" width="150" />
        <el-table-column prop="userAgent" label="浏览器" show-overflow-tooltip>
          <template #default="scope">
            <el-popover
              trigger="hover"
              placement="top"
              width="300"
            >
              <p>{{ scope.row.userAgent || '未知' }}</p>
              <template #reference>
                <span>{{ scope.row.userAgent ? getBrowserName(scope.row.userAgent) : '未知' }}</span>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="operationType" label="操作类型" width="100">
          <template #default="scope">
            <el-tag :type="getOperationTypeTagType(scope.row.operationType)">
              {{ getOperationTypeText(scope.row.operationType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operationModule" label="操作模块" width="150" />
        <el-table-column prop="operationDesc" label="操作描述" show-overflow-tooltip>
          <template #default="scope">
            <el-popover
              trigger="hover"
              placement="top"
              width="300"
            >
              <p>{{ scope.row.operationDesc || '暂无描述' }}</p>
              <template #reference>
                <span>{{ scope.row.operationDesc || '暂无描述' }}</span>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="operationResult" label="操作结果" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.operationResult === 1 ? 'success' : 'danger'">
              {{ scope.row.operationResult === 1 ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="errorMsg" label="错误信息" show-overflow-tooltip>
          <template #default="scope">
            <el-popover
              v-if="scope.row.errorMsg"
              trigger="hover"
              placement="top"
              width="400"
            >
              <pre style="white-space: pre-wrap; word-wrap: break-word;">{{ scope.row.errorMsg }}</pre>
              <template #reference>
                <el-button type="text" size="small" class="error-msg-btn">
                  查看错误
                </el-button>
              </template>
            </el-popover>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="operationTime" label="操作时间" width="180" fixed="right">
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.operationTime) }}</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'AuditLog',
  setup() {
    // 表格数据和加载状态
    const auditLogList = ref([])
    const loading = ref(false)
    
    // 搜索表单
    const searchForm = reactive({
      username: '',
      operationType: '',
      operationResult: '',
      timeRange: []
    })
    
    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 加载审计日志列表
    const loadAuditLogList = async () => {
      try {
        loading.value = true
        
        // 这里应该调用后端API获取真实数据
        // 由于是模拟环境，我们使用mock数据
        await new Promise(resolve => setTimeout(resolve, 500))
        
        // Mock审计日志数据
        const mockData = [
          {
            id: 1,
            username: '张三',
            ip: '192.168.1.100',
            userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36',
            operationType: 1,
            operationModule: '系统管理',
            operationDesc: '用户登录系统',
            operationResult: 1,
            errorMsg: '',
            operationTime: '2025-09-10 09:15:30'
          },
          {
            id: 2,
            username: '李四',
            ip: '192.168.1.101',
            userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.15',
            operationType: 3,
            operationModule: '用户管理',
            operationDesc: '新增用户：王五',
            operationResult: 1,
            errorMsg: '',
            operationTime: '2025-09-10 10:25:45'
          },
          {
            id: 3,
            username: '张三',
            ip: '192.168.1.100',
            userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36',
            operationType: 4,
            operationModule: '角色管理',
            operationDesc: '编辑角色：内容审核员',
            operationResult: 1,
            errorMsg: '',
            operationTime: '2025-09-10 11:30:20'
          },
          {
            id: 4,
            username: '王五',
            ip: '192.168.1.102',
            userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Firefox/129.0',
            operationType: 5,
            operationModule: '用户管理',
            operationDesc: '删除用户：赵六',
            operationResult: 0,
            errorMsg: '权限不足，无法删除用户',
            operationTime: '2025-09-10 13:45:10'
          },
          {
            id: 5,
            username: '李四',
            ip: '192.168.1.101',
            userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.15',
            operationType: 6,
            operationModule: '审计日志',
            operationDesc: '查询系统审计日志',
            operationResult: 1,
            errorMsg: '',
            operationTime: '2025-09-10 14:20:35'
          },
          {
            id: 6,
            username: '张三',
            ip: '192.168.1.100',
            userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36',
            operationType: 13,
            operationModule: '角色管理',
            operationDesc: '为角色：普通用户 分配权限',
            operationResult: 1,
            errorMsg: '',
            operationTime: '2025-09-10 15:10:50'
          },
          {
            id: 7,
            username: '王五',
            ip: '192.168.1.102',
            userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Firefox/129.0',
            operationType: 1,
            operationModule: '系统管理',
            operationDesc: '用户登录系统',
            operationResult: 0,
            errorMsg: '密码错误，请重新输入',
            operationTime: '2025-09-10 16:05:25'
          },
          {
            id: 8,
            username: '李四',
            ip: '192.168.1.101',
            userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.15',
            operationType: 2,
            operationModule: '系统管理',
            operationDesc: '用户退出系统',
            operationResult: 1,
            errorMsg: '',
            operationTime: '2025-09-10 17:30:40'
          }
        ]
        
        // 模拟分页
        const startIndex = (pagination.currentPage - 1) * pagination.pageSize
        const endIndex = startIndex + pagination.pageSize
        auditLogList.value = mockData.slice(startIndex, endIndex)
        pagination.total = mockData.length
        
      } catch (error) {
        console.error('加载审计日志失败:', error)
        ElMessage.error('加载审计日志失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
    
    // 处理搜索
    const handleSearch = () => {
      pagination.currentPage = 1
      loadAuditLogList()
    }
    
    // 处理重置
    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        if (key === 'timeRange') {
          searchForm[key] = []
        } else {
          searchForm[key] = ''
        }
      })
      pagination.currentPage = 1
      loadAuditLogList()
    }
    
    // 处理刷新
    const handleRefresh = () => {
      loadAuditLogList()
    }
    
    // 处理分页大小变化
    const handleSizeChange = (size) => {
      pagination.pageSize = size
      loadAuditLogList()
    }
    
    // 处理当前页码变化
    const handleCurrentChange = (current) => {
      pagination.currentPage = current
      loadAuditLogList()
    }
    
    // 处理导出
    const handleExport = async () => {
      try {
        // 这里应该调用后端API导出日志
        
        ElMessage.success('日志导出成功，文件将自动下载')
      } catch (error) {
        console.error('导出日志失败:', error)
        ElMessage.error('导出日志失败，请稍后重试')
      }
    }
    
    // 获取操作类型文本
    const getOperationTypeText = (type) => {
      const typeMap = {
        1: '登录',
        2: '登出',
        3: '新增',
        4: '编辑',
        5: '删除',
        6: '查询',
        7: '导入',
        8: '导出'
      }
      return typeMap[type] || '未知'
    }
    
    // 获取操作类型标签样式
    const getOperationTypeTagType = (type) => {
      const typeMap = {
        1: 'primary',
        2: 'info',
        3: 'success',
        4: 'warning',
        5: 'danger',
        6: 'info',
        7: 'success',
        8: 'warning'
      }
      return typeMap[type] || 'default'
    }
    
    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      // 假设dateTime已经是格式化好的字符串
      return dateTime
    }
    
    // 获取浏览器名称
    const getBrowserName = (userAgent) => {
      if (!userAgent) return '未知'
      
      if (userAgent.includes('Chrome')) {
        return 'Chrome'
      } else if (userAgent.includes('Safari') && !userAgent.includes('Chrome')) {
        return 'Safari'
      } else if (userAgent.includes('Firefox')) {
        return 'Firefox'
      } else if (userAgent.includes('Edge')) {
        return 'Edge'
      } else if (userAgent.includes('MSIE') || userAgent.includes('Trident/')) {
        return 'Internet Explorer'
      } else {
        return '其他浏览器'
      }
    }
    
    // 检查权限
    const checkPermission = (permissionCode) => {
      // 从localStorage获取用户权限
      const permissions = JSON.parse(localStorage.getItem('permissions') || '[]')
      // 检查是否包含所需权限
      return permissions.includes(permissionCode)
    }
    
    onMounted(() => {
      loadAuditLogList()
    })
    
    return {
      auditLogList,
      loading,
      searchForm,
      pagination,
      handleSearch,
      handleReset,
      handleRefresh,
      handleSizeChange,
      handleCurrentChange,
      handleExport,
      getOperationTypeText,
      getOperationTypeTagType,
      formatDateTime,
      getBrowserName,
      checkPermission
    }
  }
}
</script>

<style scoped>
.audit-log-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  overflow-x: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.error-msg-btn {
  color: #f56c6c;
  padding: 0;
  height: auto;
  min-width: 60px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .el-form--inline .el-form-item {
    width: 100%;
    margin-bottom: 12px;
  }
  
  .el-form--inline .el-input,
  .el-form--inline .el-select,
  .el-form--inline .el-date-editor {
    width: 100% !important;
  }
}
</style>